package fudan.secret.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.json.annotations.JSON;
import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.ActionSupport;

import fudan.secret.domain.User;
import fudan.secret.util.DomainConverter;
import fudan.secret.util.HibernateSessionFactory;

public class IntroduceAction extends ActionSupport{
	 private String uid;
	 private int firstResult;
	  private Map<String,String> map;
	 
	  @JSON(serialize=false)
	  public String getUid(){
		  return uid;
	  }
	  
	  public void setUid(String id){
		  uid = id;
	  }
	  
	  @JSON(serialize=false)
	  public int getFirstResult(){
		  return firstResult;
	  }
	  
	  public void setFirstResult(int result){
		  firstResult = result;
	  }
	  
	  public Map<String, String> getResult() {  
	      return map;  
	   }  
	  
	  public String execute() throws Exception{
		  Session session = HibernateSessionFactory.getSession();
		  Transaction tx = null;
		  map = new HashMap<String,String>();
		  try{
			  String sql="select b.uid_1 from follows a inner join follows b on a.uid_2=b.uid_2 and a.uid_1=:uid_1 and b.uid_1<>a.uid_1";
			  SQLQuery squery = session.createSQLQuery(sql);
			  squery.setMaxResults(10);
			  squery.setFirstResult(firstResult);
			  squery.setParameter("uid_1", uid);
			  List users = squery.list();
			  if(users != null || users.size()!=0){
				  map.put("int_num", String.valueOf(users.size()));
				  for(int i=0;i<users.size();i++){
					  Criteria crit = session.createCriteria(User.class);
					  crit.add(Restrictions.eq("uid", users.get(i)));
					  User find_user = (User)crit.uniqueResult();
					  DomainConverter dct = new DomainConverter();
					  map.put("user"+String.valueOf(i), dct.User2String(find_user));
				  }
				map.put("introduce", "true");
			  } else {
				  map.put("introduce", "false");
			  }
		  } catch(Exception e) {
			  map.put("introduce", "error");
			  e.printStackTrace();
			  tx.rollback();
		  } finally {
			  session.close();
		  }
		  return SUCCESS;
	  }
}
